package swing.frame;

import api.DictionaryApi;
import beans.Meaning;
import beans.Word;
import http.Response;
import model.ApiResultModel;
import model.SearchResultModel;
import myException.ServerConnectException;
import swing.BaseFrame;
import swing.FrameManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;

public class DesktopWordFrame extends BaseFrame {

    public final static String frameTitle = "桌面单词";

    public JPanel contentPanel;

    //当前界面显示的单词
    private JLabel wordText;
    private JTextArea meaningArea;

    private Timer timer;
    private int refreshTime; //单词刷新时间（单位：毫秒）
    public final static int MIN_REFRESH_TIME = 3; //最短刷新时间 3秒
    public final static int MAX_REFRESH_TIME = 3600; //最长刷新时间 3600秒

    @Override
    protected void initFrame() {
        this.setTitle(frameTitle);
        this.setSize(350,300);
        Dimension screenSize =Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((int)screenSize.getWidth() - 350, 0);
        contentPanel = new JPanel();
        contentPanel.setLayout(null);
        Color color = new Color(230, 240, 255);
        contentPanel.setBackground(color);
        this.setContentPane(contentPanel);
        //置于顶层
        this.setAlwaysOnTop(true);
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosed(e);
                FrameManager.offDesktopWordSwitch();
            }
        });
    }

    @Override
    protected void initAllComponent() {
        //显示的单词
        wordText = new JLabel();
        wordText.setBounds(10, 0, 280, 50);
        Font wordTextFont = new Font("宋体", Font.BOLD,25);
        wordText.setFont(wordTextFont);
        //单词含义列表
        meaningArea = new JTextArea();
        meaningArea.setBounds(12, 50, 278, 200);
        Font meaningFont = new Font("宋体", Font.PLAIN,18);
        meaningArea.setFont(meaningFont);
        meaningArea.setBackground(this.getBackground());
        meaningArea.setLineWrap(true);
        meaningArea.setEditable(false);
    }

    @Override
    protected void addAllComponent() {
        contentPanel.add(wordText);
        contentPanel.add(meaningArea);
    }

    public void showFrame(int refreshTime) {
        super.showFrame();
        this.refreshTime = refreshTime;
        startRefreshWord();
    }

    @Override
    public void hideFrame() {
        super.hideFrame();
        stopRefreshWord();
    }

    public void refreshWord(Word word, List<Meaning> meaningList) {
        wordText.setText(word.getWord_string());
        StringBuilder meaningText = new StringBuilder();
        for (Meaning meaning : meaningList) {
            meaningText.append(meaning.getWord_meaning() + "\n");
        }
        meaningArea.setText(meaningText.toString());
        //解决刷新时内容重叠的bug
        contentPanel.repaint();
    }

    public void refreshWord() {
        try {
            Response response = DictionaryApi.get_random_word();
            ApiResultModel<SearchResultModel> apiResult = ApiResultModel.fromJson(response.getBody(), SearchResultModel.class);
            SearchResultModel searchResultModel = apiResult.getResult();
            Word word = searchResultModel.getWord();
            List<Meaning> meaningList = searchResultModel.getWordMeaningList();
            SwingUtilities.invokeLater(() -> refreshWord(word, meaningList));
        } catch (ServerConnectException ignored) {
        }
    }

    private void startRefreshWord() {
        refreshWord();
        stopRefreshWord();
        timer = new Timer(refreshTime, e -> refreshWord());
        timer.start();
    }

    public void stopRefreshWord() {
        if (timer != null) {
            timer.stop();
        }
    }

    /**
     * 修改单词刷新时间
     * @param refreshTime 刷新时间
     */
    public void changeRefreshTime(int refreshTime) {
        this.refreshTime = refreshTime;
        if (timer != null && timer.isRunning()) {
            startRefreshWord();
        }
    }

    private void setRefreshTime(int time) {
        if (time < MIN_REFRESH_TIME) {
            this.refreshTime = MIN_REFRESH_TIME * 1000;
        } else if (time > MIN_REFRESH_TIME) {
            this.refreshTime = MIN_REFRESH_TIME * 1000;
        }
        this.refreshTime = time * 1000;
    }
}
